package com.electric.qrapp.ui.base.vm

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.launch

/**
 *@author created by WA03675
 *@date  2021-08-02 15:13
 *@des
 */
abstract class BaseViewModel : ViewModel() {

    val loadingLiveDate = MutableLiveData(false)
    private val reqStatus = MutableLiveData(false)

    /**
     * 所有请求用的同一个监听
     * 如果需要为每个接口不同的监听
     * 请使用 BaseRepository中的exeEveryResp
     * 这个方法不能监听具体的异常 比如token
     */
    fun launch(
        needLoading: Boolean = true,
        block: suspend () -> Unit
    ) {
        reqStatus.postValue(true)
        if (needLoading) {
            loadingLiveDate.postValue(true)
        }
        viewModelScope.launch {
            try {
                block.invoke()
            } catch (e: Throwable) {
            } finally {
                if (needLoading) {
                    loadingLiveDate.postValue(false)
                }
                reqStatus.postValue(false)
            }
        }
    }

    /*
     * 为每个接口设置单独的状态监听
     */
//    fun <T : Any> exeEveryResp(
//        block: suspend () -> BaseResponse<T>,
//        stateLiveData: StateLiveData<T>
//    ) {
//        viewModelScope.launch {
//            var baseResponse = BaseResponse<T>()
//            try {
//                baseResponse.stateEnum = RespStateEnum.LOADING
//                baseResponse = block.invoke()
//
//                when (baseResponse.code) {
//                    RespStateEnum.SUCCESS.code -> {
//                        if (baseResponse.data == null || baseResponse.data is List<*> && (baseResponse.data as List<*>).size == 0) {
//                            baseResponse.stateEnum = RespStateEnum.EMPTY
//                        } else {
//                            //请求成功并且数据为空的情况下，为STATE_SUCCESS
//                            baseResponse.stateEnum = RespStateEnum.SUCCESS
//                        }
//                    }
//
//                    RespStateEnum.BAD_TOKEN.code -> baseResponse.stateEnum = RespStateEnum.BAD_TOKEN
//
//                    else -> baseResponse.stateEnum = RespStateEnum.FAILED
//                }
//            } catch (e: Exception) {
//                baseResponse.stateEnum = RespStateEnum.ERROR
//                baseResponse.msg = e.toString()
//            } finally {
//                stateLiveData.postValue(baseResponse)
//            }
//        }
//    }

}